﻿

using Afa.Utils.Security;

namespace Afa.Utils.Operator
{
    public class UserProvider
    {
        //public static UserProvider Provider
        //{
        //    get { return new UserProvider(); }
        //}

        private static readonly string _loginUserKey = Config.Config.GetValue("_loginUserKey");
        private static readonly string _loginProvider = Config.Config.GetValue("_loginProvider");

        public static UserEntity CurrentUser
        {
            get
            {
                UserEntity currentUser = new UserEntity();
                if (_loginProvider.ToLower() == "cookie")
                {
                    if (WebHelper.GetCookie(_loginUserKey) == "")
                        return null;
                    currentUser = DESEncrypt.Decrypt(WebHelper.GetCookie(_loginUserKey)).ToObject<UserEntity>();
                }
                else if (_loginProvider.ToLower() == "session")
                {
                    currentUser = DESEncrypt.Decrypt(WebHelper.GetSession(_loginUserKey)).ToObject<UserEntity>();
                }
                else
                {
                    return null;
                }
                return currentUser;
            }
        }

        /// <summary>
        /// 保存当前用户信息
        /// </summary>
        /// <param name="currentUserEntity"></param>
        public static void AddCurrentUser(UserEntity currentUserEntity)
        {
            if (_loginProvider.ToLower() == "cookie")
            {
                WebHelper.WriteCookie(_loginUserKey, DESEncrypt.Encrypt(currentUserEntity.ToJson()), 120);
            }
            else
            {
                WebHelper.WriteSession(_loginUserKey, DESEncrypt.Encrypt(currentUserEntity.ToJson()));
            }
        }

        public static void RemoveCurrentUser()
        {
            if (_loginProvider.ToLower() == "cookie")
            {
                WebHelper.RemoveCookie(_loginUserKey.Trim());
            }
            else
            {
                WebHelper.RemoveSession(_loginUserKey.Trim());
            }
        }
    }
}
